angular.module('U9ImHd.services')

.factory('InitService', ['$rootScope', '$q', '$ionicPlatform', '$ionicHistory', '$cordovaToast', '$timeout', 'AppManager', 'User', 'Help', 'APPCONSTANTS',
    function($rootScope, $q, $ionicPlatform, $ionicHistory, $cordovaToast, $timeout, AppManager, User, Help, APPCONSTANTS) {
        var defer = $q.defer();

        init();

        return defer.promise;

        function init () {
            $ionicPlatform.registerBackButtonAction(
                onHardwareBackButton,
                APPCONSTANTS.platformBackButtonPriorityView
            );

            $rootScope.$on('responseError', function (e, err) {
                alert(err.message);
            });

            publishExternalAPI();

            var tasks = [AppManager.loaded, User.loaded];
            $q.all(tasks).finally(function() {
                defer.resolve();
            });
        }

        function publishExternalAPI () {
            var u9ImHd = window.u9ImHd || (window.u9ImHd = {});

            u9ImHd.getFullPath = Help.getFullPath;
            u9ImHd.registerModule = registerModule;
        }

        function registerModule (moduleName, dependencies) {
            var module = angular.module(moduleName, dependencies || []);
            angular.module('U9ImHd').requires.push(moduleName);
            return module;
        }

        var _confirmExit = false;
        function onHardwareBackButton(e) {
            if ($ionicHistory.backView()) {
                $ionicHistory.goBack();
            } else {
                if (_confirmExit) {
                    ionic.Platform.exitApp();
                } else {
                    _confirmExit = true;
                    $cordovaToast.showShortBottom('再按一次退出');
                    $timeout(function () {
                        _confirmExit = false;
                    }, APPCONSTANTS.exitAppConfirmTime);
                }
            }

            e.preventDefault();
            return false;
        }
    }
]);
